package com.yicong.taxi.api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.yicong.taxi.BuildConfig;
import com.yicong.taxi.api.interceptor.Level;
import com.yicong.taxi.api.interceptor.LoggingInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.internal.platform.Platform;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 *
 *
 */
public class ApiClient {

    // 默认连接时间（秒）
    private static final int DEFAULT_CONNECT_TIME = 30;

    private static ApiService financeRetrofit;
    protected static final Object monitor = new Object();
    private static OkHttpClient client;
    private static Retrofit retrofit;

    private ApiClient() {
    }

    static {
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
                .create();

        client = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_CONNECT_TIME, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_CONNECT_TIME, TimeUnit.SECONDS)
                .readTimeout(DEFAULT_CONNECT_TIME, TimeUnit.SECONDS)
//                .addInterceptor(chain -> {//添加请求头部消息
//                    Request request = chain.request()
//                        .newBuilder().addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
//                        .addHeader("Accept-Encoding", "gzip, deflate")
//                        .addHeader("Connection", "keep-alive")
//                        .addHeader("Accept", "*/*")
//                        .addHeader("Cookie", "add cookies here")
////                            .addHeader("Host","api.ibopt.cn")
//                            .addHeader("User-Agent","android")
//                        .build();
//                    return chain.proceed(request);
//                    })
                .addInterceptor(new LoggingInterceptor.Builder()//打印请求响应日志
                        .loggable(BuildConfig.DEBUG)
                        .setLevel(Level.BODY)
                        .log(Platform.INFO).build())
                .build();

        retrofit = new Retrofit.Builder()
                        .baseUrl(Api.BASEADDRESS)
                        .client(client)
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .build();

    }

    public static ApiService getApiRetrofitInstance() {
        synchronized (monitor) {
            if (financeRetrofit == null) {
                financeRetrofit = retrofit.create(ApiService.class);
            }
            return financeRetrofit;
        }
    }
}
